package com.dehui.traders.ui.stockdetail.chart;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.dehui.traders.R;
import com.dehui.traders.bean.BaseListResponse;
import com.dehui.traders.kchart.DataParse;
import com.dehui.traders.kchart.KLineManager;
import com.dehui.traders.kchart.MyCombinedChart;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.ui.stockdetail.StocksDetailActivity;
import com.dehui.traders.ui.OptionHelper;
import com.dehui.traders.utils.ThreadTask;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.goldze.mvvmhabit.utils.KLog;
import retrofit2.Call;
import retrofit2.Response;

public class KDetailFragment extends Fragment {

    private View view;
    private MyCombinedChart mChartKline;
    private MyCombinedChart mChartKVolume;
    public List<String[]> mKList = new ArrayList<>();
    private String code;
    private String market;
    private String close;
    private boolean mBsSelect = true;
    private DataParse mData;
    private LinearLayout llK;
    private RelativeLayout rlLoading;
    private StocksDetailActivity mActivity;
    private KLineManager kLineManager;
    private boolean isComplete;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (view == null){
            view = inflater.inflate(R.layout.fragment_detail_k,null);
        }else{
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null)
                parent.removeView(view);
        }

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = (StocksDetailActivity) getActivity();
        Bundle bundle = getArguments();
        code = bundle.getString("code");
        market = bundle.getString("market");
        close = bundle.getString("close");
        initViews();
        initLesionr();
        if (mKList != null && mKList.size() > 0){
            initKLine();
        }else{
            getRiK();
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int type = msg.what;
            if (type == 1){
                List<String[]> list = (List<String[]>) msg.obj;
                if (mKList.size() <= 0){
                    mKList.clear();
                    mKList.addAll(list);
                    initKLine();
                }
            }
            if (type == 2){
                if (getActivity() == null || getActivity().isFinishing())
                    return;
                rlLoading.setVisibility(View.GONE);
                llK.setVisibility(View.VISIBLE);
                KLineManager.getInstange().initKLine(getContext(), mChartKline, mChartKVolume, mData);
                isComplete = true;
            }

        }
    };

    private void initViews() {
        mChartKline = view.findViewById(R.id.mycombinedchart_k_line);
        mChartKVolume = view.findViewById(R.id.mycombinedchart_k_volume);
        llK = view.findViewById(R.id.ll_k);
        rlLoading = view.findViewById(R.id.rl_loading);
    }

    public void getRiK() {
        if (mKList == null || mKList.size() <= 0){
            getCacheK();
            getHistoryRiK();
        }else{
            initKLine();
        }
    }

    /**
     * 获取今日k线图值
     */
    private void getTodayRiK() {
        Call<BaseListResponse<String[]>> call = NetImpl.getTodayBussinessLabelPoint(market + code);
        call.enqueue(new CallListener<BaseListResponse<String[]>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<String[]>> response) {
                BaseListResponse<String[]> baseListResponse = response.body();
                if (baseListResponse.status == 200){
                    List<String[]> list = baseListResponse.result;
                    Collections.reverse(list);
                    mKList.addAll(list);
                    OptionHelper.saveKLine(getActivity(),code,new Gson().toJson(mKList));
                    initKLine();
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    /**
     * 获取历史K线图值
     */
    private void getHistoryRiK() {
        Call<BaseListResponse<String[]>> call = NetImpl.getKBussinessLabelPoint(market + code);
        call.enqueue(new CallListener<BaseListResponse<String[]>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<String[]>> response) {
                BaseListResponse<String[]> baseListResponse = response.body();
                if (baseListResponse.status == 200){
                    List<String[]> list = baseListResponse.result;
                    Collections.reverse(list);
                    mKList.clear();
                    mKList.addAll(list);
                    if (getActivity() != null && !getActivity().isFinishing())
                        OptionHelper.saveKLine(getActivity(),code,new Gson().toJson(mKList));
                    initKLine();
                    getTodayRiK();
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }


    private void getCacheK() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                List<String[]> list = OptionHelper.getKLine(getActivity(), code);
                if (list != null){
                    Message message = mHandler.obtainMessage();
                    message.obj = list;
                    message.what = 1;
                    mHandler.sendMessage(message);
                }
            }
        },ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    private void initKLine() {
        if (mData == null){
            mData = new DataParse();
        }
        ThreadTask.getInstance().executorOtherThread(new Runnable() {
            @Override
            public void run() {
                mData.parseKLineBS(mKList,mBsSelect);
                mHandler.sendEmptyMessage(2);
            }
        },10);
    }

    private void initLesionr() {
        mChartKline.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                Highlight highlight = new Highlight(h.getXIndex(), h.getValue(), h.getDataIndex(), h.getDataSetIndex());

                float touchY = h.getTouchY() - mChartKline.getHeight();
                Highlight h1 = mChartKVolume.getHighlightByTouchPoint(h.getXIndex(), touchY);
                highlight.setTouchY(touchY);
                if (null == h1) {
                    highlight.setTouchYValue(0);
                } else {
                    highlight.setTouchYValue(h1.getTouchYValue());
                }
                mChartKVolume.highlightValues(new Highlight[]{highlight});
                mActivity.showKView(h.getXIndex(),mData);
            }

            @Override
            public void onNothingSelected() {
               mActivity.dimissKView();
               mChartKVolume.highlightValue(null);
            }
        });

        mChartKVolume.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                Highlight highlight = new Highlight(h.getXIndex(), h.getValue(), h.getDataIndex(), h.getDataSetIndex());

                float touchY = h.getTouchY() + mChartKline.getHeight();
                Highlight h1 = mChartKline.getHighlightByTouchPoint(h.getXIndex(), touchY);
                highlight.setTouchY(touchY);
                if (null == h1) {
                    highlight.setTouchYValue(0);
                } else {
                    highlight.setTouchYValue(h1.getTouchYValue());
                }
                mChartKline.highlightValues(new Highlight[]{highlight});
                mActivity.showKView(h.getXIndex(),mData);
            }

            @Override
            public void onNothingSelected() {
                mActivity.dimissKView();
                mChartKline.highlightValue(null);
            }
        });
    }


    public void setBs(boolean selected) {
        mBsSelect = selected;
        if (isComplete)
            initKLine();
    }
}
